package cn.basic.org.service.impl;

import cn.basic.common.service.impl.IBaseServiceImpl;
import cn.basic.org.domain.Department;
import cn.basic.org.dto.DepartmentDTO;
import cn.basic.org.mapper.DepartmentMapper;
import cn.basic.org.service.IDepartmentService;
import cn.basic.org.vo.result.DepartmentVo;
import cn.basic.org.vo.query.DepartmentQuery;
import cn.basic.utils.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @description: IDepartmentServiceImpl
 * @date: 2023/3/1 15:22
 * @author: ZhaoLc
 * @version: 1.0
 */
@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class IDepartmentServiceImpl extends IBaseServiceImpl<Department,DepartmentQuery,DepartmentVo> implements IDepartmentService {

    @Resource
    DepartmentMapper departmentMapper;

    @Transactional(rollbackFor = Exception.class)
    public Integer add(DepartmentDTO departmentDTO) {
        // 设置时间
        departmentDTO.setCreateTime(new Date());
        departmentDTO.setUpdateTime(new Date());
        // 插入部门
        Department department = departmentDTO.getDepartment();
        departmentMapper.insert(department);
        departmentDTO.setId(department.getId());
        // 获取部门路径path属性
        departmentDTO = setPath(departmentDTO);
        return departmentMapper.update(departmentDTO.getDepartment());
    }

    @Transactional(rollbackFor = Exception.class)
    public Integer update(DepartmentDTO departmentDTO) {
        // 设置时间
        departmentDTO.setUpdateTime(new Date());
        departmentDTO = setPath(departmentDTO);
        return departmentMapper.update(departmentDTO.getDepartment());
    }

    /**
     * 获取父部门路径
     * @param departmentDTO 部门dto
     * @return DepartmentDTO
     */
    public DepartmentDTO setPath(DepartmentDTO departmentDTO){
        String path="";
        if(departmentDTO.getParent()!=null&&Objects.nonNull(departmentDTO.getParent().getId())){
            DepartmentVo parent = departmentMapper.loadVoById(departmentDTO.getParent().getId());
            path = parent.getPath();
        }
        path = path+"/"+departmentDTO.getId();
        departmentDTO.setPath(path);
        return departmentDTO;
    }

    @Override
    public Department getByIdNoParent(Serializable id) {
        return departmentMapper.loadByIdNoParent(id);
    }

}
